package com.zr.service.dispatch.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zr.dao.base.BaseCityDao;
import com.zr.dao.car.CarInfoDao;
import com.zr.dao.dispatch.DispatchRouteDao;
import com.zr.dao.dispatch.DispatchTicketDao;
import com.zr.dao.dispatch.DispatchTicketOrderDao;
import com.zr.dao.order.OrderFormDao;
import com.zr.exception.BusinessException;
import com.zr.service.dispatch.DispatchTicketService;
import com.zr.utils.SequenceUtil;
import com.zr.utils.TokenUtil;
import com.zr.vo.base.BaseCity;
import com.zr.vo.car.CarInfo;
import com.zr.vo.dispatch.DispatchRoute;
import com.zr.vo.dispatch.DispatchTicket;
import com.zr.vo.dispatch.DispatchTicketOrder;
import com.zr.vo.order.OrderForm;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
 * @author Administrator
 */
import java.util.*;

@Service
public class DispatchTicketServiceImpl implements DispatchTicketService {
    @Resource
    private DispatchTicketDao dispatchTicketDao;
    @Resource
    private DispatchRouteDao dispatchRouteDao;
    @Resource
    private DispatchTicketOrderDao dispatchTicketOrderDao;
    @Resource
    private SequenceUtil sequenceUtil;
    @Resource
    private TokenUtil tokenUtil;
    @Resource
    private CarInfoDao carInfoDao;
    @Resource
    private BaseCityDao baseCityDao;
    @Resource
    private OrderFormDao orderFormDao;

    /**
     * 条件查询调度单列表
     *
     * @param dispatchTicket
     * @return
     * @author 陈鹏
     */
    @Override
    public PageInfo<DispatchTicket> list(DispatchTicket dispatchTicket) {
        PageHelper.startPage(dispatchTicket.getPageNum(), dispatchTicket.getPageSize());
        List<DispatchTicket> dispatchTicketList = dispatchTicketDao.list(dispatchTicket);
        return new PageInfo<DispatchTicket>(dispatchTicketList);
    }

    /**
     * 新增调度单
     *
     * @param dispatchTicket
     * @return
     * @author 陈鹏
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int add(DispatchTicket dispatchTicket) throws BusinessException {
        //生成订单id,创建人,创建时间,当前状态改变时间,车牌号,起点城市,终点城市
        dispatchTicket.setTicketId(this.getNewDispatchIdRedis());
        Date date = new Date();
        dispatchTicket.setCreateTime(date);
        dispatchTicket.setCreateId(tokenUtil.currentUserId());
        dispatchTicket.setStatusTime(date);
        dispatchTicket.setCarNumber(dispatchTicket.getCarInfo().getNumber());
        dispatchTicket.setStartAreaName(baseCityDao.selectByPrimaryKey(dispatchTicket.getStartAreaId()).getCityName());
        dispatchTicket.setEndAreaName(baseCityDao.selectByPrimaryKey(dispatchTicket.getEndAreaId()).getCityName());
        int flag = dispatchTicketDao.insertSelective(dispatchTicket);
        //更新路线表
        List<DispatchRoute> dispatchRouteList = dispatchTicket.getDispatchRouteList();
        for (int i = 0; i < dispatchRouteList.size(); i++) {
            DispatchRoute dispatchRoute = dispatchRouteList.get(i);
            dispatchRoute.setTicketId(dispatchTicket.getTicketId());
            dispatchRouteDao.insertSelective(dispatchRoute);
        }
        //更新订单调度单中间表
        this.addOrderFormList(dispatchTicket);

        if ("待领取".equals(dispatchTicket.getStatus())) {
            this.submit(dispatchTicket);
        }
        return flag;
    }

    /**
     * 删除调度单
     *
     * @param dispatchTicket
     * @return
     * @author 陈鹏
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int remove(DispatchTicket dispatchTicket) {
        //删除路线表
        dispatchRouteDao.deleteByTicketId(dispatchTicket.getTicketId());
        //删除调度单订单中间表
        dispatchTicketOrderDao.deleteByTicketId(dispatchTicket.getId());
        DispatchTicket dispatchTicket1 = new DispatchTicket();
        dispatchTicket1.setId(dispatchTicket.getId());
        dispatchTicket1.setDel(0);
        return dispatchTicketDao.updateByPrimaryKeySelective(dispatchTicket1);
    }

    /**
     * 更新调度单
     *
     * @param dispatchTicket
     * @return
     * @author 陈鹏
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(DispatchTicket dispatchTicket) throws BusinessException {
        //修改人,修改时间,当前状态改变时间
        Date date = new Date();
        dispatchTicket.setStatusTime(date);
        dispatchTicket.setModifyTime(date);
        dispatchTicket.setModifyId(tokenUtil.currentUserId());
        //撤销调度单
        if ("已取消".equals(dispatchTicket.getStatus())) {
            CarInfo carInfo = new CarInfo();
            carInfo.setId(dispatchTicket.getCarInfo().getId());
            carInfo.setCarStatus("空闲");
            carInfoDao.updateCarStatus(carInfo);
            // 更新订单表
            List<OrderForm> orderFormList = dispatchTicket.getOrderFormList();
            if (orderFormList != null && orderFormList.size() != 0) {
                for (OrderForm orderForm : orderFormList) {
                    OrderForm orderForm1 = new OrderForm();
                    orderForm1.setId(orderForm.getId());
                    orderForm1.setCurrentStatus("待调度");
                    orderForm1.setOrderTicketId(null);
                    orderFormDao.updateByPrimaryKeySelective(orderForm1);
                }
            }

            return dispatchTicketDao.updateByPrimaryKeySelective(dispatchTicket);
        }
        dispatchTicket.setCarNumber(dispatchTicket.getCarInfo().getNumber());
        dispatchTicket.setStartAreaName(baseCityDao.selectByPrimaryKey(dispatchTicket.getStartAreaId()).getCityName());
        dispatchTicket.setEndAreaName(baseCityDao.selectByPrimaryKey(dispatchTicket.getEndAreaId()).getCityName());
        //更新路线表,先删除后增加
        dispatchRouteDao.deleteByTicketId(dispatchTicket.getTicketId());
        List<DispatchRoute> dispatchRouteList = dispatchTicket.getDispatchRouteList();
        dispatchRouteDao.insertDispatchRouteList(dispatchRouteList);
        //更新中间表,先删除后增加
        dispatchTicketOrderDao.deleteByTicketId(dispatchTicket.getId());
        this.addOrderFormList(dispatchTicket);
        if ("待领取".equals(dispatchTicket.getStatus())) {
            dispatchTicket.setStatusTime(date);
            this.submit(dispatchTicket);

        }
        return dispatchTicketDao.updateByPrimaryKeySelective(dispatchTicket);
    }

    /**
     * 查询所有调度单状态及其数量
     *
     * @return
     * @author 张荣颜
     */
    @Override
    public List<DispatchTicket> statusList() {
        return dispatchTicketDao.statusList();
    }

    /* 查询当日新增调度单数量
     * @return
     * @author 张荣颜
     */
    @Override
    public int getTodayAddQuantity() {
        return dispatchTicketDao.getTodayAddQuantity();
    }

    /* 查询最近6个月每个月的调度单数量
     * @return
     * @author 张荣颜
     */
    @Override
    public List<String> getChangeOfDispatchQuantitySixMonths() {
        return dispatchTicketDao.getChangeOfDispatchQuantitySixMonths();
    }

    /* 查询没有完成的调度单数量
     * @return
     * @author 张荣颜
     */
    @Override
    public int getDispatchUnfinishedQuantity() {
        return dispatchTicketDao.getDispatchUnfinishedQuantity();
    }

    /**
     * 查询所有运输中调度单
     *
     * @return List<DispatchTicket>
     */
    @Override
    public PageInfo<DispatchTicket> listForTransportation(DispatchTicket dispatchTicket) {
        PageHelper.startPage(dispatchTicket.getPageNum(), dispatchTicket.getPageSize());
        List<DispatchTicket> dispatchTicketList = dispatchTicketDao.listForTransportation(dispatchTicket);
        return new PageInfo<DispatchTicket>(dispatchTicketList);
    }

    /**
     * 利用redis获取新增调度单编号
     *
     * @return String
     * @author 陈鹏
     */
    private String getNewDispatchIdRedis() {
        StringBuffer sb = new StringBuffer();
        String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = "DT" + currentDate;
        long incr = sequenceUtil.incr(key, 1);
        String code = SequenceUtil.getSequence(incr, 4);
        return sb.append(key).append(code).toString();
    }

    /**
     * 更新订单调度单中间表
     *
     * @param dispatchTicket
     * @author 陈鹏
     */
    private void addOrderFormList(DispatchTicket dispatchTicket) {
        List<OrderForm> orderFormList = dispatchTicket.getOrderFormList();
        if (orderFormList != null && orderFormList.size() != 0) {
            for (OrderForm orderForm : orderFormList) {
                DispatchTicketOrder dispatchTicketOrder = new DispatchTicketOrder();
                dispatchTicketOrder.setDicpatchId(dispatchTicket.getId());
                dispatchTicketOrder.setOrderId(orderForm.getId());
                dispatchTicketOrderDao.insertSelective(dispatchTicketOrder);
            }
        }

    }

    /**
     * 直接提交表单时操作将任务状态变为待提货,司机状态变为任务待领取
     *
     * @param dispatchTicket
     * @author 陈鹏
     */
    private void submit(DispatchTicket dispatchTicket) throws BusinessException {
        List<OrderForm> orderFormList = dispatchTicket.getOrderFormList();
        //更新车辆状态
        CarInfo carInfo = new CarInfo();
        carInfo.setId(dispatchTicket.getCarInfo().getId());
        carInfo.setCarStatus("任务待领取");
        if (carInfoDao.updateCarStatus(carInfo) == 0) {
            throw new BusinessException("司机已被派发订单");
        }
        // 更新订单表
        for (OrderForm orderForm : orderFormList) {
            OrderForm orderForm1 = new OrderForm();
            orderForm1.setId(orderForm.getId());
            orderForm1.setCurrentStatus("待提货");
            orderForm1.setOrderTicketId(dispatchTicket.getTicketId());
            if (orderFormDao.updateCurrentStatus(orderForm1) == 0) {
                throw new BusinessException(orderForm1.getOrderId() + "订单已被派发");
            }
        }
    }

    /**
     * 查询最近7天的调度单数量
     *
     * @return
     */
    @Override
    public Map getTicketDoneRecentWeek() {
        //获取日历对象
        Calendar calendar = Calendar.getInstance();
        //调整到7天以前
        calendar.add(Calendar.DAY_OF_MONTH, -6);
        Map<String, Object> map = new HashMap();
        List<String> dayList = new ArrayList<>();
        List<Integer> numList = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            Date date = calendar.getTime();
            Integer result = dispatchTicketDao.getDelayNumByDate(date);
            numList.add(result);
            //循环7次获取7天
            Integer month = calendar.get(Calendar.MONTH) + 1;
            Integer day = calendar.get(Calendar.DAY_OF_MONTH);
            String str = month + "-" + day;
            dayList.add(str);
            //每次日期+1
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        map.put("sdata", numList);
        map.put("xdata", dayList);
        return map;
    }


    @Override
    public Map getTicketDoneRecentMonth() {
        //获取日历对象
        Calendar calendar = Calendar.getInstance();
        Date end = calendar.getTime();
        //调整到上个月
        calendar.add(Calendar.MONTH, -1);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        Date begin = calendar.getTime();
        int j = (int) ((end.getTime() - begin.getTime()) / (1000 * 3600 * 24)) + 1;
        Map<String, Object> map = new HashMap();
        List<String> dayList = new ArrayList<>();
        List<Integer> numList = new ArrayList<>();
        for (int i = 0; i < j; i++) {
            Date date = calendar.getTime();
            Integer result = dispatchTicketDao.getDelayNumByDate(date);
            numList.add(result);
            //循环j次获取j天
            Integer month = calendar.get(Calendar.MONTH) + 1;
            Integer day = calendar.get(Calendar.DAY_OF_MONTH);
            String str = month + "-" + day;
            dayList.add(str);
            //每次日期+1
            calendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        map.put("sdata", numList);
        map.put("xdata", dayList);
        return map;
    }

    @Override
    public Map getTicketDoneThisYear() {
        //获取日历对象
        Calendar calendar = Calendar.getInstance();
        int j = calendar.get(Calendar.MONTH) + 1;
        //调整到1月
        calendar.set(Calendar.MONTH, 0);
        Map<String, Object> map = new HashMap();
        List<String> monthList = new ArrayList<>();
        List<Integer> numList = new ArrayList<>();
        for (int i = 0; i < j; i++) {
            Date date = calendar.getTime();
            Integer result = dispatchTicketDao.getDelayNumByMonth(date);
            numList.add(result);
            //循环j次获取j个月
            Integer year = calendar.get(Calendar.YEAR);
            Integer month = calendar.get(Calendar.MONTH) + 1;
            String str = year + "-" + month;
            monthList.add(str);
            //每次月份+1
            calendar.add(Calendar.MONTH, 1);
        }
        map.put("sdata", numList);
        map.put("xdata", monthList);
        return map;
    }

    /* 查询最近一年每个月的调度单数量
     * @return
     * @author 张荣颜
     */
    @Override
    public List<String> getChangeOfDispatchQuantityYear() {
        return dispatchTicketDao.getChangeOfDispatchQuantityYear();
    }

    /* 查询最近30天每天的的调度单数量
     * @return
     * @author 张荣颜
     */
    @Override
    public List<String> getChangeOfDispatchQuantityOneMonth() {
        return dispatchTicketDao.getChangeOfDispatchQuantityOneMonth();
    }
}
